<?php
namespace app\api\logic;

use think\Model;
use app\api\Util\CCPHelper;
use think\Db;

class UserLogic extends Model
{
    /**
     * 注册容联云子账号
     * @param  $friendlyName 子账号名称
     */
    public function create_sub_account($cons_id = '', $friendlyName = '')
    {
        $ccp_helper = new CCPHelper;
        $result = $ccp_helper->createSubAccount($friendlyName);

        if (!isset($result) || isset($result->statusCode)) {
            //  111150子账号已存在
            if ($result->statusCode == '111150') {
                $friendlyName = $friendlyName.'a';
                $result = $this->create_sub_account($cons_id, $friendlyName);
                return $result;
            } else {
                return $result->statusMsg;
            }
        } else {
        	$info['cons_id'] = $cons_id;
        	$info['addtime'] = $result->dateCreated;
        	$info['voipAccount'] = $result->voipAccount;
        	$info['voipPwd'] = $result->voipPwd;
        	$info['friendlyName'] = $result->friendlyName;
        	$info['subAccountSid'] = $result->subAccountSid;
        	$info['subToken'] = $result->subToken;
        	Db::table('ronglian_account')->insert($info);
        	return $result;
        }
    }

    /**
     * 获取容联云子账号
     * @param  $cons_id      用户id
     * @param  $friendlyName 注册时的账号名称
     * @return [type]               [description]
     */
    public function user_sub_account($cons_id = '', $friendlyName = '')
    {
    	$user_account = Db::table('ronglian_account')->where('cons_id', $cons_id)->find();
    	if (!isset($user_account)) {
    		$user_account = $this->create_sub_account($cons_id, $friendlyName);
    	}
    	$result = $this->get_ronglian_sign();
    	$user_account['timeStamp'] = $result['timeStamp'];
    	$user_account['sig'] = $result['sig'];
    	return $user_account;
    }

    /**
     * 容联云登录sig、时间戳
     * @return [type] [description]
     */
    public function get_ronglian_sign()
    {
    	$appId= config('ccp_appId');
	    $apptoken= config('ccp_appToken');
	    $timeStamp = date('YmdHis');
        $userName = 'liu';
        
        $sig = md5($appId.$userName.$timeStamp.$apptoken);

        $return['sig'] = $sig;
        $return['timeStamp'] = $timeStamp;
        return $return;
    }

    





}